package com.ndp.fb.walle.controller;

import com.alibaba.fastjson.JSON;
import com.ndp.fb.enums.ErrorType;
import com.ndp.fb.rdb.model.version.VersionInfo;
import com.ndp.fb.util.StringUtil;
import com.ndp.fb.walle.business.VersionInfoService;
import com.ndp.fb.walle.model.vo.OutputResult;
import com.ndp.fb.walle.model.vo.versionInfo.result.VersionInfoVo;
import com.ndp.fb.walle.util.ResponseUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by elvisxiong on 16/2/29.
 */
@RequestMapping("/versionInfo")
@RestController
public class VersionInfoController {
    private final org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    VersionInfoService versionInfoService;

    @RequestMapping(value = "/getVersionInfoList", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<String> getVersionInfo(String param, HttpServletRequest req, HttpServletResponse rep) {
        Map<String, String> paramMap = StringUtil.parseParamsToMap(param);
        ErrorType errorType = null;
        String languageCode = paramMap.get("language");
        if(StringUtil.isEmpty(languageCode)){
            languageCode = "zh-cn";
        }
        List<VersionInfoVo> versionInfoVos = new ArrayList<>();
        try{
            List<VersionInfo> versionInfoList = versionInfoService.getVersionInfo(languageCode);

            for(VersionInfo versionInfo:versionInfoList){
                String body = versionInfo.getBody().replaceAll("\n","<br />");
                versionInfo.setBody(body);
                VersionInfoVo versionInfoVo = new VersionInfoVo(versionInfo);
                versionInfoVos.add(versionInfoVo);
            }
            if(versionInfoVos == null ){
                errorType = ErrorType.Version_Info_Not_Exist;
            }

        }catch (Exception ex){
            logger.error("load version list error:",ex);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, versionInfoVos);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

}
